package com.example.saas.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.saas.domain.DataSource;
import com.example.saas.mapper.DataSourceMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class DataSourceServiceImpl extends ServiceImpl<DataSourceMapper, DataSource> {

    @Resource
    private javax.sql.DataSource dataSource;
    @Resource
    private DefaultDataSourceCreator dataSourceCreator;

    /**
     * 获取数据源列表
     */
    public List<DataSource> getDataSourceList() {
        List<DataSource> list = new ArrayList<>();
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        Set<String> actDataSources = ds.getDataSources().keySet();
        List<DataSource> dataSourceList = this.baseMapper.selectList(null);
        if(CollUtil.isNotEmpty(dataSourceList)){
           list = dataSourceList.stream().peek(i->{
               if(CollUtil.isNotEmpty(actDataSources) && actDataSources.contains(i.getKey())){
                   i.setStatus("2");
               }
           }).collect(Collectors.toList());
        }
        return list;
    }


    /**
     * 添加数据源
     */
    public void addDataSource(DataSource dataSourceDTO){
        // 测试数据源
        // 向数据库添加数据源数据
        this.baseMapper.insert(dataSourceDTO);
        // 向动态数据源种添加数据源
        String key = dataSourceDTO.getKey();
        DataSourceProperty property = new DataSourceProperty();
        BeanUtil.copyProperties(dataSourceDTO, property);
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        javax.sql.DataSource newDataSource = dataSourceCreator.createDataSource(property);
        ds.addDataSource(key, newDataSource);
    }


    /**
     * 删除数据源
     * @param key 数据源Key
     */
    public void del(String key){
        // 从数据库种删除
        this.baseMapper.delete(new LambdaQueryWrapper<DataSource>().eq(DataSource::getKey,key));
        // 从动态数据源种删除
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        ds.removeDataSource(key);
    }

}
